<?php

/**
 * Description of Application_Model_Csv
 *
 * @author Jean Brito
 */
abstract class Application_Model_Csv extends Application_Model_Fix {

	protected $_dir = '/../public/data/csv/';
	protected $_fieldName=null;
	public function __construct() {
		$fd=explode('/',trim($this->_dir,"/"));
		$file="./";
		foreach($fd as $dir){
			$file.=$dir;
			if(!is_dir($file))
				mkdir($file);
			$file.="/";
		}
		$filename=$file.$this->_table;
		$this->_fileName=$filename;

		if(!file_exists($filename)){
			$this->write();
		}
		
		$this->read();

		parent::__construct();
	}

	public function write(){
		$fo=fopen($this->_fileName,'w');
		$header="";
		foreach($this->_fields as $fld=>$field)
			$header.=$field['name'].";";
		fwrite($fo,$header."\r\n");

		foreach($this->_data as $row){
			$line="";
			foreach($this->_fields as $fld=>$field){
				$line.=$row[$field['name']].";";
			}
			fwrite($fo,$line."\r\n");
		}

		fclose($fo);
	}

	public function read(){
		$rows=explode("\r\n",file_get_contents($this->_fileName));
		foreach($rows as $i=>$r)if($i>0)if(strlen($r)){
			$row=explode(";",$r);$lrow=array();$f=0;
			foreach($this->_fields as $field){
				$lrow[$field['name']]=$row[$f++];
			}
			$this->_data[]=$lrow;
		}
	}

	public function post($params) {
		$result=parent::post($params);
		$line="";
		foreach($result['data'] as $value)
			$line.=$value.";";

		$fo=fopen($this->_fileName,'a');
		fwrite($fo,$line."\r\n");
		fclose($fo);

		return $result;
	}

	public function delete($id) {
		$result=parent::delete($id);
		$this->write();
		return $result;
	}

	public function put($id, $params) {
		$result=parent::put($id,$params);
		$this->write();
		return $result;
	}

}
